// fileName      :  user.go
// createdAt     :  2021-10-19
// description   :

package models

import (
	"go.uber.org/zap"
	"time"
	"zl-gin/controllers/v1/params"
	"zl-gin/my_error"
	"zl-gin/mysql"
	"zl-gin/mysql/models/internal"
	"zl-gin/utils"
)

type UserResult struct {
	Id       string `json:"id"`
	UserName string `json:"userName"`
	Password string `json:"password"`
	Email    string `json:"email"`
}

//GetUserInfoByName 根据用户名获取用户信息
func GetUserInfoByName(name string) (*UserResult, *my_error.MyError) {
	user := &UserResult{}
	rows := mysql.GetDbInstance().Model(internal.Users{}).Where("user_name=?", name).Find(user).RowsAffected
	if rows <= 0 {
		zap.L().Error("查询用户信息失败, 用户不存在 ", zap.String("name", name))
		return nil, my_error.NewMyError(my_error.ErrCodeRecordNotFound)
	}
	return user, nil
}

//CheckUserExistsByEmail 根据用户名获取用户信息
func CheckUserExistsByEmail(email string) bool {
	user := &UserResult{}
	rows := mysql.GetDbInstance().Model(&internal.Users{}).Where("email=?", email).Find(user).RowsAffected
	if rows <= 0 {
		return false
	}
	return true
}

//UserRegister 用户注册
func UserRegister(data params.UserRegisterParam) *my_error.MyError {
	//先检查Email是否存在
	has := CheckUserExistsByEmail(data.Email)
	if has {
		return my_error.NewMyErrorCustomer(-3, "Email已注册，请更换")
	}
	id, idErr := utils.GetSnowFlakeId(1)
	if idErr != nil {
		return my_error.NewMyError(my_error.ErrCodeGenerateIdFail)
	}
	createAt := time.Now()
	user := &internal.Users{
		BaseModel: internal.BaseModel{
			ID:        id,
			CreatedAt: createAt,
			UpdatedAt: createAt,
		},
		UserName: data.UserName,
		Password: utils.HashAndSalt([]byte(data.Password)),
		Email:    data.Email,
	}
	res := mysql.GetDbInstance().Create(user).Error
	if res != nil {
		return my_error.NewMyErrorCustomer(-2, "用户注册失败")
	}
	return nil
}
